#!/usr/bin/python

from comm import *
import sys, pickle, re

STA_STARTED = 1
STA_STOPPED = 0

class ctrlLector(commLector):
      def __init__(self, addr):
          self.idEquip = ''
          self.connectat = False
          self.vars = {}
          self.config = {}
          self.started = False

          try:
             commLector.__init__(self, addr)
          except Exception, e:
             raise Exception, str(e) #"No hem puc connectar al servidor!"
             return 

          if not self.connectar():
             raise IOError, "No he pogut iniciar la sessio amb el servidor"
             return
          else:
             self.connectat = True   
             self.status = self.getStatus()
             self.started = (self.status == STA_STARTED) 
 
      def getId(self):
          if self.connectat:
             if self.enviar("GETID"):
                self.idEquip = self.rebre()

          return self.idEquip               
 
      def getConf(self):
          if self.connectat:
             if self.enviar("GETCONF"):
                self.config = pickle.loads(self.rebre())
         
          return self.config

      def getVars(self):
          if self.connectat:
             if self.enviar("GETVARS"):
                self.vars = pickle.loads(self.rebre())

          return self.vars
 
      def getDefs(self):
          if self.connectat:
             if self.enviar("GETDEFS"):
                self.defs = pickle.loads(self.rebre())

          return self.defs
 
      def start(self):
          retval = False

          if self.connectat:
             if self.enviar("START"):
                resp = self.rebre()
                retval = (resp=="START\tOK\r")
                
                self.started = True
                        
          return retval
        
      def getStatus(self):
          retval = -1

          if self.connectat:
             if self.enviar("STATUS"):
                resp = self.rebre() 
                if resp.startswith("STARTED"):
                   retval = STA_STARTED
                else: 
                   retval = STA_STOPPED
  
          return retval 

      def desconnecta(self):
          if self.connectat:
             if self.enviar("QUIT"):
                resp = self.rebre()
                if (resp=="DISCONNECTED!\r"):
                   self.s.close()
                   self.connectat = False
